import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/data/user_address.dart';

class UserAddressModel extends ChangeNotifier {
  List<UserAddress> _addresses = [];
  bool _isLoading = false;
  String _errorMessage = '';

  List<UserAddress> get addresses => _addresses;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  bool get hasAddresses => _addresses.isNotEmpty;

  // 重置加载状态
  void resetLoadStatus() {
    _isLoading = false;
    _errorMessage = '';
    notifyListeners();
  }

  // 加载用户地址列表
  Future<void> loadUserAddresses(GraphQLClient client) async {
    try {
      _isLoading = true;
      _errorMessage = '';
      notifyListeners();

      final result = await client.query(
        QueryOptions(
          document: gql(UserGQL.fetchUserAddresses),
          fetchPolicy: FetchPolicy.networkOnly
        ),
      );

      if (result.hasException) {
        _errorMessage = '获取地址列表失败: ${result.exception.toString()}';
        debugPrint('获取地址列表失败: ${result.exception.toString()}');
      } else {
        // 解析地址数据
        final addressesData = result.data!['user']['currentUser']['addresses'] as List?;
        print("获取到地址数据: $addressesData");
        _addresses = addressesData != null
            ? addressesData.map((item) => UserAddress.fromJson(item)).toList()
            : [];
      }
    } catch (e) {
      _errorMessage = '加载地址列表失败: $e';
      debugPrint('加载地址列表异常: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 清空地址列表
  void clearAddresses() {
    _addresses.clear();
    notifyListeners();
  }
}